<template>
  <div class="h-full">
    <!--    <vxe-card title="" class="w-full" :border="false">-->
    <!--      <AuForm ref="formRef" :formList="formList" @submit="search" />-->
    <!--    </vxe-card>-->
    <el-tabs
      v-model="activeName"
      type="border-card"
      class="h-full"
      @tab-click="handleClick"
    >
      <el-tab-pane :label="$t('menus.storeNotice')" name="Store" class="h-full">
        <AuTable
          v-if="activeName === 'Store'"
          ref="tableRef"
          v-bind="gridOption"
          @actionClick="actionClick"
        >
          <template #status_default="{ row }">
            {{
              row.net_status == 1
                ? $t("device_manage.form.online")
                : $t("device_manage.form.offline")
            }}
          </template>
        </AuTable>
      </el-tab-pane>
      <el-tab-pane
        :label="$t('menus.deviceNotice')"
        name="Device"
        class="h-full"
      >
        <AuTable
          v-if="activeName === 'Device'"
          ref="tableRef"
          v-bind="gridOption"
          @actionClick="actionClick"
        />
      </el-tab-pane>
      <el-tab-pane
        :label="$t('menus.deviceBreakdown')"
        name="DevBreakdown"
        class="h-full"
      >
        <AuTable
          v-if="activeName === 'DevBreakdown'"
          ref="tableRef"
          v-bind="gridOption"
          @actionClick="actionClick"
        >
          <template #store_default="{ row }">
            {{ storeKeyValue[row.storeId] }}
          </template>
        </AuTable>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import {
  getCurrentInstance,
  onBeforeMount,
  onMounted,
  reactive,
  ref
} from "vue";
import { AuTable } from "@/components/AuTable";
import { AuForm } from "@/components/AuForm";
import {
  ACTION_TYPE,
  ObjectProps,
  PropDefines
} from "@/components/AuTable/type";
import { FormulaListProp } from "@/api/teaInfuser/formula";
import {
  deviceGetList,
  DeviceProp,
  faultRecordGetList,
  FaultRecordProp,
  faultRecordUpd
} from "@/api/teaInfuser/device";
import {
  handleDeviceStatus,
  handleEmptyDeviceStore,
  handleStoreStatus
} from "@/layout/components/lay-navbar/notice";
import { TabsPaneContext } from "element-plus";
import dayjs from "dayjs";
import { getStoreList } from "@/api/teaInfuser/store";
import { useI18n } from "vue-i18n";

defineOptions({
  name: "StatusNotice"
});

// region 声明ref变量集合
// const formList = ref([]);
const { proxy } = getCurrentInstance();
const { t } = useI18n();
const gridOption = reactive<PropDefines>({
  isServerPage: true,
  showExportBtn: false,
  columns: [
    { field: "store_name", title: "device_manage.form.store_name" },
    {
      field: "net_status",
      title: "device_manage.form.status",
      slots: { default: "status_default" }
    },
    { field: "device_num", title: "device_manage.form.device_count" }
  ],
  actions: [],
  operateTools: [],
  dataSource: []
});

const columnDevice = [
  { field: "device_id", title: "device_manage.form.device_code" },
  { field: "store_name", title: "device_manage.form.store_name" },
  {
    field: "reason",
    title: "device_manage.form.error_reason"
  },
  {
    field: "activation_time",
    title: "device_manage.form.activation_time",
    width: 190
  }
];
const columnStore = [
  { field: "store_name", title: "device_manage.form.store_name" },
  {
    field: "net_status",
    title: "device_manage.form.status",
    slots: { default: "status_default" }
  },
  { field: "device_num", title: "device_manage.form.device_count" }
];
const columnDevBreakdown = [
  { field: "deviceId", title: "device_manage.form.device_code" },
  {
    field: "storeName",
    title: "device_manage.form.store_name",
    slots: { default: "store_default" }
  },
  {
    field: "desc",
    title: "device_manage.form.error_reason"
  },
  {
    field: "faultTimeMillisecond",
    title: "device_manage.form.fault_time",
    width: 190,
    formatter({ cellValue }) {
      return dayjs(cellValue).format("YYYY-MM-DD HH:mm:ss");
    }
  }
];
const operateList = [
  {
    key: "",
    name: "table.processed",
    onClick: (v: FaultRecordProp) => {
      proxy.$auMessageBox
        .confirm(
          t("device_manage.form.confirm_action", {
            action: t("table.processed"),
            device: v.deviceId
          }),
          t("notice.title")
        )
        .then(() => {
          const param = {
            id: v.id,
            handleStatus: 1
          };
          faultRecordUpd(param).then(async () => {
            proxy.$message.success(
              t("notice.operation_success", {
                action: t("table.processed")
              })
            );
            await initOffDevBreakdown();
            gridOption.dataSource = dataDevBreakdown.value;
          });
        });
    }
  }
];

const activeName = ref("Store");
const dataStore = ref([]);
const dataDevice = ref([]);
const dataDevBreakdown = ref<FaultRecordProp[]>([]);

const storeKeyValue = ref({});
// const formRef = ref();
const tableRef = ref();
// endregion

// region 公共方法的集合

const initOffStore = () => {
  deviceGetList({
    start_page: 0,
    size: 0
  }).then(async res => {
    const deviceSt = res.data.filter(v => v.device_id.includes("ATT-S"));
    const storeMap = handleStoreStatus(deviceSt, 0);
    const offData = [];
    storeMap.forEach((value, key) => {
      if (Array.isArray(value) && value.length > 0) {
        offData.push({
          ...value[0],
          device_num: value.length
        });
      }
    });
    const emptyList = await handleEmptyDeviceStore();
    const handleEmp = emptyList.map(v => {
      v.store_name = v.name;
      return v;
    });
    dataStore.value = [...offData, ...handleEmp];

    gridOption.dataSource = dataStore.value;
  });
};

const initOffDevice = () => {
  deviceGetList({
    start_page: 0,
    size: 0
  }).then(async res => {
    const deviceSt = res.data.filter(v => v.device_id.includes("ATT-S"));
    const deviceList = await handleDeviceStatus(deviceSt);
    dataDevice.value = deviceList ?? [];
  });
};

const initOffDevBreakdown = async () => {
  const res = await faultRecordGetList({
    start_page: 0,
    size: 0,
    faultRecord: {
      handleStatus: 0
    }
  });
  dataDevBreakdown.value = res.data;
};

const getStoreData = async () => {
  const res = await getStoreList({
    start_page: 1,
    size: 0
  });
  for (const item of res.data) {
    storeKeyValue.value[item.id] = item.name;
  }
};
// endregion

// region 组件事件的集合
const handleClick = (tab: TabsPaneContext) => {
  const name = tab.paneName;

  if (name === "Store") {
    gridOption.columns = columnStore;
    gridOption.dataSource = dataStore.value;
    gridOption.operateTools = [];
  } else if (name === "DevBreakdown") {
    gridOption.columns = columnDevBreakdown;
    gridOption.dataSource = dataDevBreakdown.value;
    gridOption.operateTools = operateList;
  } else {
    gridOption.columns = columnDevice;
    gridOption.dataSource = dataDevice.value;
    gridOption.operateTools = [];
  }
};

type ActionType = {
  key: ACTION_TYPE;
  row: FormulaListProp;
};
const actionClick = ({ key, row }: ActionType) => {
  console.log(key, row);
};
// endregion
onBeforeMount(() => {
  getStoreData();
});

onMounted(() => {
  initOffStore();
  initOffDevice();
  initOffDevBreakdown();
});
</script>

<style scoped>
:deep(.el-tabs--border-card > .el-tabs__content) {
  padding: 0;
}

:deep(.el-tabs__content) {
  height: calc(100% - 60px);
}
</style>
